/*
 *
 *
 *
 */
package com.cms.controller.admin;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cms.constant.CommonConstant;
import com.cms.domain.Feedback;
import com.cms.entity.Admin;
import com.cms.entity.AdminRole;
import com.cms.service.AdminRoleService;
import com.cms.service.AdminService;
import com.cms.service.RoleService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;


/**
 * Controller - 管理员
 *
 *
 *
 */
@Controller("adminAdminController")
@RequestMapping("/admin/admin")
public class AdminController extends BaseController {

	@Autowired
	private AdminService adminService;

	@Autowired
	private RoleService roleService;

	@Autowired
	private AdminRoleService adminRoleService;

	/**
	 * 列表
	 */
	@RequestMapping
	public String index(String name, String username, Integer pageNumber, ModelMap modelMap){
		setListQuery();
		if(pageNumber==null){
			pageNumber = 1;
		}
		modelMap.addAttribute("page", adminService.findPage(name,username,pageNumber,PAGE_SIZE));
		modelMap.addAttribute("name", name);
		modelMap.addAttribute("username", username);
		return getView("admin/index");
	}

	/**
	 * 检查用户名是否存在
	 */
	@ResponseBody
	@RequestMapping("/checkUsername")
	public Boolean checkUsername(String username) {
		if (StringUtils.isEmpty(username)) {
			return false;
		}
		return !adminService.usernameExists(username);
	}

	/**
	 * 添加
	 */
	@RequestMapping("/add")
	public String add(ModelMap modelMap) {
		modelMap.addAttribute("roles", roleService.findAll());
		return getView("admin/add");
	}

	/**
	 * 保存
	 */
	@RequestMapping("/save")
	public String save(Admin admin,Integer[] roleIds) {
		if (adminService.usernameExists(admin.getUsername())) {
			return CommonConstant.ADMIN_ERROR_VIEW;
		}
		admin.setPassword(DigestUtils.md5Hex(admin.getPassword()));
		admin.setCreateDate(LocalDateTime.now());
		admin.setUpdateDate(LocalDateTime.now());
		adminService.save(admin);
        for(Integer roleId : roleIds){
        	AdminRole adminRole = new AdminRole();
        	adminRole.setAdminId(admin.getId());
        	adminRole.setRoleId(roleId);
			adminRoleService.save(adminRole);
        }
		return "redirect:"+getListQuery("/admin/admin");
	}

	/**
	 * 编辑
	 */
	@RequestMapping("/edit")
	public String edit(Integer id,ModelMap modelMap) {
		List<AdminRole> list = adminRoleService.list(new LambdaQueryWrapper<AdminRole>().eq(AdminRole::getAdminId, id));
		// 使用 Stream 将 adminId 拼接起来
		String roleIds = list.stream()
				.map(AdminRole::getRoleId) // 获取每个 AdminRole 的 roleId
				.map(String::valueOf) // 将 adminId 转换为 String
				.collect(Collectors.joining(",")); // 使用逗号连接所有 adminId

		modelMap.addAttribute("admin", adminService.getById(id));
		modelMap.addAttribute("roles", roleService.findAll());
		modelMap.addAttribute("roleIds", roleIds);
		return getView("admin/edit");
	}

	/**
	 * 更新
	 */
	@RequestMapping("/update")
	public String update(Admin admin,Integer[] roleIds) {
		Admin pAdmin = adminService.getById(admin.getId());
		if (pAdmin == null) {
			return CommonConstant.ADMIN_ERROR_VIEW;
		}
		if (StringUtils.isNotEmpty(admin.getPassword())) {
			admin.setPassword(DigestUtils.md5Hex(admin.getPassword()));
		} else {
			admin.setPassword(pAdmin.getPassword());
		}
		admin.setUpdateDate(LocalDateTime.now());
		adminService.updateById(admin);
		adminRoleService.deleteByAdminId(admin.getId());
        for(Integer roleId : roleIds){
        	AdminRole adminRole = new AdminRole();
        	adminRole.setAdminId(admin.getId());
        	adminRole.setRoleId(roleId);
			adminRoleService.save(adminRole);
        }
		return "redirect:"+getListQuery("/admin/admin");
	}

	/**
	 * 重置密码
	 */
	@ResponseBody
	@RequestMapping("/reset")
	public Feedback reset(Integer id,ModelMap modelMap){
		Admin admin = adminService.getById(id);
		admin.setPassword(DigestUtils.md5Hex("123456"));
		admin.setUpdateDate(LocalDateTime.now());
		adminService.updateById(admin);
		return Feedback.success(new HashMap<>());
	}

	/**
	 * 删除
	 */
	@ResponseBody
	@RequestMapping("/delete")
	public Feedback delete(Integer ids[]) {
		if(ArrayUtils.isNotEmpty(ids)){
			for(Integer id:ids){
				adminService.removeById(id);
			}
		}
		return Feedback.success(new HashMap<>());
	}

}